#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Handler for the server's layer configuration page.

The configuration page provides an interface to changing the supported layers.

  Data: Returns the data needed by the configuration page to render
        the interface.
  DefaultList: Returns the layers.default data needed by the client-side
               LayerManager.
  Page: Renders the configuration template.
  Remove: Removes the specified layer.
"""

__author__ = 'jasonstredwick@google.com (Jason Stredwick)'


# Disable 'Import not at top of file' lint error.
# pylint: disable-msg=C6204
try:
  import auto_import_fixer
except ImportError:
  pass  # This will fail on unittest, ok to pass.

from layer.handlers import helper

import simplejson

# Disable 'Import not at top of file' lint error.
# pylint: disable-msg=C6204
try:
  from google.appengine.ext import webapp
  from google.appengine.ext.webapp.util import run_wsgi_app
except ImportError:
  from google.appengine.ext import webapp
  from google.appengine.ext.webapp.util import run_wsgi_app


class Data(webapp.RequestHandler):
  """Handles request for the Layer UX configuration page's data."""

  def get(self):
    """Handles a get request, redirects to the post request."""
    self.post()

  def post(self):
    """Handles a post request."""
    layers = helper.GetAllSortedLayers()
    data = [layer.ToDict() for layer in layers]
    output = simplejson.dumps(data)
    self.response.out.write(output)


class DefaultList(webapp.RequestHandler):
  """Handles request for the layers.default data.

  The layers.default data is used by the client-side LayerManager to determine
  what layers to load.
  """

  def get(self):
    """Handles a get request, redirects to the post request."""
    self.post()

  def post(self):
    """Handles a post request."""
    layers = helper.GetAllSortedLayers()
    data = [layer.url for layer in layers]
    output = simplejson.dumps({'layers': data})
    self.response.out.write(output)


class Page(webapp.RequestHandler):
  """Handles request for the Layer UX configuration page."""

  def get(self):
    """Handles a get request, redirects to the post request."""
    self.post()

  def post(self):
    """Handles a post request."""
    output = helper.RenderTemplate('config.html')
    self.response.out.write(output)


class Remove(webapp.RequestHandler):
  """Handles request to remove a simple layer."""

  def get(self):
    """Handles a get request, redirects to the post request."""
    self.post()

  def post(self):
    """Handles a post request.

    Returns the rendered page for the simple editor for a new layer.
    """
    # TODO(jasonstredwick): Change string literal to constant.
    output = 'Failed'

    layer = helper.FindLayer(self.request.get('url'))
    if layer:
      layer.delete()
      # TODO(jasonstredwick): Change string literal to constant.
      output = 'Removed'

    self.response.out.write(output)


def main():
  application = webapp.WSGIApplication([('/layer/config', Page),
                                        ('/layer/config/data', Data),
                                        ('/layer/config/default_list',
                                         DefaultList),
                                        ('/layer/config/remove', Remove)
                                       ],
                                       debug=True)
  run_wsgi_app(application)


if __name__ == '__main__':
  main()

